# apps/tags/serializers.py
from rest_framework import serializers
from .models import Tag


class TagSerializer(serializers.ModelSerializer):
    """
    标签序列化器
    用于序列化 Tag 模型，支持读取和写入操作
    """

    class Meta:
        model = Tag
        fields = [
            'id',
            'name',
            'category',
            'description',
            'used_count',
            'created_at',
            'updated_at',
        ]
        read_only_fields = ['id', 'used_count', 'created_at', 'updated_at']


class TagCreateUpdateSerializer(serializers.ModelSerializer):
    """
    标签创建/更新专用序列化器
    可用于 POST/PUT/PATCH 请求
    """

    class Meta:
        model = Tag
        fields = [
            'id',
            'name',
            'category',
            'description',
        ]
        # id 为只读，name 和 category 联合唯一
        read_only_fields = ['id']

    def validate(self, attrs):
        name = attrs.get('name')
        category = attrs.get('category')

        # 检查唯一性
        queryset = Tag.objects.filter(name=name, category=category)
        if self.instance:
            queryset = queryset.exclude(pk=self.instance.pk)

        if queryset.exists():
            raise serializers.ValidationError({
                'name': '该标签名称与分类的组合已存在。',
                'category': '该标签名称与分类的组合已存在。'
            })
        return attrs


class TagListSerializer(serializers.ModelSerializer):
    """
    标签列表序列化器（可选，用于自定义列表响应）
    """
    class Meta:
        model = Tag
        fields = ['id', 'name', 'category', 'used_count','created_at','updated_at']

class TagDetailSerializer(serializers.ModelSerializer):
    """
    标签详情序列化器（可选，显式定义只读字段）
    """
    class Meta:
        model = Tag
        fields = '__all__'